package com.tes;

import java.util.ArrayList;
import java.util.List;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.ZoomCamera;
import org.anddev.andengine.engine.camera.hud.HUD;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXLayer;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXLoader;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXObject;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXObjectGroup;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTiledMap;
import org.anddev.andengine.entity.layer.tiled.tmx.util.exception.TMXLoadException;
import org.anddev.andengine.entity.modifier.MoveModifier;
import org.anddev.andengine.entity.primitive.Rectangle;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.ChangeableText;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.font.FontFactory;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.ui.activity.BaseGameActivity;
import org.anddev.andengine.util.Debug;
import android.graphics.Color;

public class TesGame1 extends BaseGameActivity {

	// ukuran layar
	static final int CAMERA_WIDTH = 480;
	static final int CAMERA_HEIGHT = 320;

	// camera and tiledmap
	private ZoomCamera mCamera;
	private TMXTiledMap mTMXTiledMap;

	// score
	private BitmapTextureAtlas tHighScore;
	private Font mHighScore;

	// player
	private BitmapTextureAtlas tPlayer;
	private TiledTextureRegion mPlayer;

	// control
	private BitmapTextureAtlas tControlBase;
	private TextureRegion mControlBase;

	private BitmapTextureAtlas tControlKnob;
	private TextureRegion mControlKnob;

	@Override
	public Engine onLoadEngine() {
		final int maxWidth = CAMERA_WIDTH * 2;
		final int maxHeight = CAMERA_HEIGHT * 2;

		this.mCamera = new ZoomCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		this.mCamera.setBounds(0, maxWidth, 0, maxHeight);
		this.mCamera.setBoundsEnabled(true);
		return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE,
				new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT),
				this.mCamera));
	}

	@Override
	public void onLoadResources() {
		// set path
		FontFactory.setAssetBasePath("font/");
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");

		// high score
		tHighScore = new BitmapTextureAtlas(128, 128,
				TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA);
		mHighScore = FontFactory.createFromAsset(tHighScore, this,
				"Alpha Flight.ttf", 24, true, Color.RED);

		// player
		tPlayer = new BitmapTextureAtlas(128, 128,
				TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA);
		mPlayer = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(
				tPlayer, this, "hero.png", 0, 0, 3, 4);

		// control
		tControlBase = new BitmapTextureAtlas(128, 128,
				TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA);
		mControlBase = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				tControlBase, this, "control_base.png", 0, 0);

		tControlKnob = new BitmapTextureAtlas(64, 64,
				TextureOptions.REPEATING_BILINEAR_PREMULTIPLYALPHA);
		mControlKnob = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				tControlKnob, this, "control_knob.png", 0, 0);

		// load resource
		mEngine.getTextureManager().loadTextures(tHighScore, tPlayer,
				tControlBase, tControlKnob);
		mEngine.getFontManager().loadFont(mHighScore);
	}

	@Override
	public Scene onLoadScene() {
		this.mEngine.registerUpdateHandler(new FPSLogger());

		final Scene mScene = new Scene();
		final HUD hud = new HUD();
		final List<Rectangle> listRectangle = new ArrayList<Rectangle>();

		// load the tmx file
		try {
			final TMXLoader tmxLoader = new TMXLoader(this,
					this.mEngine.getTextureManager(), // TextureOptions.BILINEAR_PREMULTIPLYALPHA,
					TextureOptions.NEAREST);
			this.mTMXTiledMap = tmxLoader.loadFromAsset(this, "coba.tmx");
		} catch (final TMXLoadException tmxle) {
			Debug.e(tmxle);
		}

		// add the non-object layers to the scene
		for (int i = 0; i < this.mTMXTiledMap.getTMXLayers().size(); i++) {
			TMXLayer layer = this.mTMXTiledMap.getTMXLayers().get(i);
			if (!layer.getTMXLayerProperties().containsTMXProperty("tembok",
					"true")) {
				mScene.attachChild(layer);
			}
		}

		// add object to the scene
		for (int i = 0; i < this.mTMXTiledMap.getTMXObjectGroups().size(); i++) {
			TMXObjectGroup objectGroup = this.mTMXTiledMap.getTMXObjectGroups()
					.get(i);
			if (objectGroup.getTMXObjectGroupProperties().containsTMXProperty(
					"tembok", "true")) {
				for (TMXObject tmxObject : objectGroup.getTMXObjects()) {
					Rectangle rectangle = new Rectangle(tmxObject.getX(),
							tmxObject.getY(), tmxObject.getWidth(),
							tmxObject.getHeight());
					listRectangle.add(rectangle);
				}
			}
		}

		// player
		final AnimatedSprite sPlayer = new AnimatedSprite(0,
				mPlayer.getHeight(), mPlayer);
		sPlayer.registerUpdateHandler(new IUpdateHandler() {

			@Override
			public void reset() {
			}

			@Override
			public void onUpdate(float pSecondsElapsed) {

			}
		});

		mScene.attachChild(sPlayer);
		mCamera.setChaseEntity(sPlayer);

		// high score
		final ChangeableText cText = new ChangeableText(CAMERA_WIDTH - 50, 10,
				mHighScore, "200");
		hud.attachChild(cText);

		// control
		final float centerControlX = 10 + mControlBase.getWidth() / 2;
		final float centerControlY = CAMERA_HEIGHT
				- (mControlBase.getHeight() / 2 + 10);

		// knob
		final Sprite sControlKnob = new Sprite(centerControlX
				- mControlKnob.getWidth() / 2, centerControlY
				- mControlKnob.getHeight() / 2, mControlKnob);

		// base + on touch event
		final Sprite sControlBase = new Sprite(centerControlX
				- mControlBase.getWidth() / 2, centerControlY
				- mControlBase.getHeight() / 2, mControlBase) {
			@Override
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
					final float pTouchAreaLocalX, final float pTouchAreaLocalY) {

				final float x = pSceneTouchEvent.getX() - centerControlX;
				final float y = pSceneTouchEvent.getY() - centerControlY;
				final long[] durasi = { 50, 50, 50 };

				final MoveModifier movePlayer1 = new MoveModifier(1,
						sPlayer.getX(),
						sPlayer.getX() + (pTouchAreaLocalX * 2),
						sPlayer.getY(), sPlayer.getY() + (pTouchAreaLocalY * 2));

				new MoveModifier(1, sPlayer.getX(), sPlayer.getX() - (x / 10),
						sPlayer.getY(), sPlayer.getY() - (y / 10));

				IUpdateHandler handlerPlayer = new IUpdateHandler() {

					@Override
					public void reset() {
						// TODO Auto-generated method stub

					}

					@Override
					public void onUpdate(float pSecondsElapsed) {
						for (Rectangle rectangle : listRectangle) {
							if (sPlayer.collidesWith(rectangle)) {

								float centerX1 = sPlayer.getX()
										+ (sPlayer.getWidth() / 2);
								float centerY1 = sPlayer.getX()
										+ (sPlayer.getWidth() / 2);

								float centerX2 = rectangle.getX()
										+ (rectangle.getWidth() / 2);
								float centerY2 = rectangle.getY()
										+ (rectangle.getHeight() / 2);

								sPlayer.clearEntityModifiers();
								sPlayer.registerEntityModifier(new MoveModifier(
										1, sPlayer.getX(), sPlayer.getX()
												+ (centerX1 - centerX2),
										sPlayer.getY(), sPlayer.getY()
												+ (centerY1 - centerY2)));
							}
						}
					}
				};

				if (pSceneTouchEvent.isActionDown()
						|| pSceneTouchEvent.isActionMove()) {
					if (pSceneTouchEvent.isActionDown())
						hud.attachChild(sControlKnob);

					sPlayer.clearEntityModifiers();
					sPlayer.clearUpdateHandlers();
					sPlayer.registerEntityModifier(movePlayer1);
					sPlayer.registerUpdateHandler(handlerPlayer);

					if ((x * x) >= (y * y)) {
						if (x > 0)
							sPlayer.animate(durasi, 6, 8, true);
						else
							sPlayer.animate(durasi, 3, 5, true);
					} else {
						if (y > 0)
							sPlayer.animate(durasi, 0, 2, true);
						else
							sPlayer.animate(durasi, 10, 12, true);
					}
				}

				if (pSceneTouchEvent.isActionUp()) {
					sPlayer.clearEntityModifiers();
					sPlayer.clearUpdateHandlers();
					hud.detachChild(sControlKnob);

					if ((x * x) >= (y * y)) {
						if (x > 0)
							sPlayer.animate(durasi, 6, 8, false);
						else
							sPlayer.animate(durasi, 3, 5, false);
					} else {
						if (y > 0)
							sPlayer.animate(durasi, 0, 2, false);
						else
							sPlayer.animate(durasi, 10, 12, false);
					}
				}

				return true;
			}
		};

		hud.attachChild(sControlBase);
		hud.registerTouchArea(sControlBase);
		hud.setTouchAreaBindingEnabled(true);

		this.getEngine().getCamera().setHUD(hud);

		mScene.setTouchAreaBindingEnabled(true);

		return mScene;
	}

	@Override
	public void onLoadComplete() {
		// TODO Auto-generated method stub
	}

}
